#include "appfileprovider.h"

#include <QDir>
#include <QApplication>

#if defined(Q_OS_LINUX)
#   include <wordexp.h>
static const char * p_expand(const char* path)
{
    wordexp_t exp_result;
    wordexp(path, &exp_result, 0);
    return exp_result.we_wordv[0];
}

#endif

bool AppFileProvider::createConfigDir()
{
#if defined(Q_OS_WIN32)
    const char* appDataPath = getenv("APPDATA");
    QString cfgPath = QString("%1\\%2")
            .arg(appDataPath)
            .arg(QApplication::applicationName());

#elif defined(Q_OS_LINUX)
    QString cfgPath = QString("%1/%2")
            .arg("~/.config")
            .arg(QApplication::applicationName());
    cfgPath = p_expand(qPrintable(cfgPath));
#else
    return false;
#endif

    if ( !QDir(cfgPath).exists() )
        return QDir().mkdir(cfgPath);
    return true;
}

QString AppFileProvider::getConfigFile(QString fname)
{
#if defined(Q_OS_WIN32)
    const char* appDataPath = getenv("APPDATA");
    return doFallback(QString("%1\\%2\\%3")
            .arg(appDataPath)
            .arg(QApplication::applicationName())
            .arg(fname), fname);
#elif defined(Q_OS_LINUX)
    QString userPath = QString("%1/%2/%3")
            .arg("~/.config")
            .arg(QApplication::applicationName())
            .arg(fname);
    QString sharePath = QString("%1/%2/%3")
            .arg("/usr/share")
            .arg(QApplication::applicationName())
            .arg(fname);

    userPath = p_expand(qPrintable(userPath));
    return doFallback(userPath, sharePath);
#else
    return fname;
#endif
}

QString AppFileProvider::doFallback(QString file1, QString file2)
{
    if ( file2.isEmpty() || QFile::exists(file1) )
        return file1;
    return file2;
}
